package netty.io.demo.RPC.server;

import netty.io.demo.RPC.utils.CommonUtils;
import netty.io.demo.RPC.utils.Constants;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NettyServer {
  private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
  
  public static void main(String[] args) {
    try {
      ServerSocket serverSocket = new ServerSocket();
      serverSocket.bind(new InetSocketAddress(Constants.PORT));
      
      executorService.execute(new ServerTask(serverSocket.accept()));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  private static class ServerTask implements Runnable {
    
    private Socket socket;
    
    public ServerTask(Socket socket) {
      this.socket = socket;
    }
    
    @Override
    public void run() {
      try {
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
        Object o = CommonUtils.transferObject(CommonUtils.inputStream2Bytes(in));
        
        System.out.println(o);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
}
